package base.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author zjw
 * @date 2022/7/22 9:45
 * @des 文件资源读取
 */
public class ResourceLoader {
    private ResourceLoader() {
    }

    /**
     * 使用 / 格式化字符串，比如文件路径
     * @param paths a b c d
     * @return  a/b/c/d
     */
    public static String combine(String... paths) {
        if (paths == null || paths.length <= 0) {
            return null;
        }
        return String.join("/", Arrays.asList(paths));
    }

    /**
     * 格式化读取文件资源
     * @param resoursePath 文件资源路径
     * @return 原样读取文本资源
     * @throws Exception
     */
    public static String load(String resoursePath) throws Exception {
        return String.join("\r\n", loadList(resoursePath));
    }

    public static List<String> loadList(String resoursePath) throws Exception {
        if (resoursePath == null || resoursePath.isEmpty()) {
            throw new Exception("resource path of resource load is empty!");
        }
        InputStream inputStream = ResourceLoader.class.getClassLoader().getResourceAsStream(resoursePath);
        if (inputStream == null) {
            throw new Exception("input stream from resourse path is null! resourse path is " + resoursePath);
        }
        List<String> result = new ArrayList<>();
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String s = bufferedReader.readLine();
            while (s != null) {
                result.add(s);
                s = bufferedReader.readLine();
            }
        }
        return result;
    }
}

